CFLAGS  += -fno-builtin -nostdinc -m32
CFLAGS	+= $(shell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1 && echo -fno-stack-protector)

LDFLAGS	+= -m $(shell $(LD) -V | grep elf_i386 2>/dev/null)

OBJCOPY := $(GCCPREFIX)objcopy
OBJDUMP := $(GCCPREFIX)objdump

# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

# kernel

ARCHINCLUDE	:= arch/x86/drivers  \
               arch/x86/include  \
               arch/x86/debug    

ARCHSRCDIR	:= arch/x86/kernel   \
               arch/x86/lib 	    \
		       arch/x86/drivers  \
		       arch/x86/debug    \
               arch/x86/mm

ARCHINCLUDE 	:= $(foreach dir,$(ARCHINCLUDE),$(addprefix -I,$(dir)))
ARCHCFLAGS		:= $(ARCHINCLUDE)

$(call add_files_cc,$(call listf_cc,$(ARCHSRCDIR)),arch_kernel,$(ARCHCFLAGS))

ARCHOBJS	= $(call read_packet,arch_kernel)

# create kernel target
kernel = $(call totarget,kernel)

$(kernel): $(ARCHOBJS) $(OBJS)
	@echo + ld $@
	$(V)$(LD) $(LDFLAGS) -T arch/x86/kernel.ld -o $@ $(ARCHOBJS) $(OBJS)
	@$(OBJDUMP) -S $@ > $(call asmfile,kernel)
	@$(OBJDUMP) -t $@ | $(SED) '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > $(call symfile,kernel)

$(call create_target,kernel)

# -------------------------------------------------------------------

# create bootblock
bootfiles = $(call listf_cc, arch/x86/boot)
$(foreach f,$(bootfiles),$(call cc_compile,$(f),$(CC),$(CFLAGS) -Os -nostdinc $(ARCHCFLAGS)))

bootblock = $(call totarget,bootblock)

$(bootblock): $(call toobj,$(bootfiles)) | $(call totarget,sign)
	@echo + ld $@
	$(V)$(LD) $(LDFLAGS) -N -e start -Ttext 0x7C00 $^ -o $(call toobj,bootblock)
	@$(OBJDUMP) -S $(call objfile,bootblock) > $(call asmfile,bootblock)
	@$(OBJCOPY) -S -O binary $(call objfile,bootblock) $(call outfile,bootblock)
	@$(call totarget,sign) $(call outfile,bootblock) $(bootblock)

$(call create_target,bootblock)

# -------------------------------------------------------------------

# create 'sign' tools
$(call add_files_host,tools/sign.c,sign,sign)
$(call create_target_host,sign,sign)

# -------------------------------------------------------------------

# create ucore.img
UCOREIMG	:= $(call totarget,ucore.img)

$(UCOREIMG): $(kernel) $(bootblock)
	$(V)dd if=/dev/zero of=$@ count=10000
	$(V)dd if=$(bootblock) of=$@ conv=notrunc
	$(V)dd if=$(kernel) of=$@ seek=1 conv=notrunc

$(call create_target,ucore.img)

# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

$(call finish_all)
